package com.preparation.controller;

import com.preparation.domain.User;
import com.preparation.dto.R;
import com.preparation.service.IUserService;
import com.preparation.untils.JwtUtil;
import com.preparation.untils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private IUserService userService;

    // 注册
    @PostMapping("/register")
    public R register(@RequestBody User user) {
        return userService.register(user);
    }

    //登录
    @GetMapping("/login")
    public R login(String username, String password){
        User user = new User(username, password);
        R r = userService.login(user);
        if (r.getCode() == 200){
            User u = (User) r.getData();
            //登录成功 生成JWT令牌
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", u.getId());
            claims.put("username", u.getUsername());
            String token = JwtUtil.genToken(claims);      //生成token

            r.setData(token);
        }
        return r;
    }

    //根据token查询用户信息
    @GetMapping("/userInfo")
    public R userInfo(){
        //从ThreadLocal中获取数据
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");

        //根据用户名查询用户信息
        User user = userService.findByUsername(username);
        return user != null ? R.success(user, "查询成功") : R.error(404, "查询失败");
    }

    // 修改用户信息
    @PutMapping
    public R updateById(@RequestBody User user) {
        boolean flag = userService.updateById(user);
        return flag ? R.success("修改成功") : R.error();
    }

    // 删除用户
    @DeleteMapping("/{id}")
    public R deleteById(@PathVariable Integer id) {
        boolean flag = userService.removeById(id);
        return flag ? R.success("删除成功") : R.error();
    }

    // 根据id查询
    @GetMapping("/{id}")
    public R getById(@PathVariable Integer id){
        User user = userService.getById(id);
        return user != null ? R.success(user, "查询成功") : R.error(404, "该用户不存在！");
    }
}
